package com.shenhangye.pushlive.filter

import android.content.Context
import android.opengl.GLES11Ext
import android.opengl.GLES30

import com.shenhangye.pushlive.R
import com.shenhangye.pushlive.util.OpenGLUtils

class CameraFilter(context: Context) : BaseFilter(context, R.raw.camera_vert, R.raw.camera_fra) {


    private var matrix: FloatArray=FloatArray(1)

    private var mFrameBuffers: IntArray=IntArray(1)

    private var mFrameBufferTextures: IntArray=IntArray(1)
    fun setMatrix(matrix: FloatArray?) {
        this.matrix = matrix!!
    }

    override fun setSize(width: Int, height: Int) {
        super.setSize(width, height)
        GLES30.glGenFramebuffers(mFrameBuffers.size, mFrameBuffers, 0)

        //2、创建属于fbo的纹理
        mFrameBufferTextures = IntArray(1)

        //创建纹理
        OpenGLUtils.glGenTextures(mFrameBufferTextures,GLES30.GL_TEXTURE_2D)

        GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, mFrameBufferTextures[0])
        GLES30.glTexImage2D(
            GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA, mWidth, mHeight,
            0, GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, null
        )

        GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFrameBuffers[0])
        GLES30.glFramebufferTexture2D(
            GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0,
            GLES30.GL_TEXTURE_2D, mFrameBufferTextures[0], 0
        )

        GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
        GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
    }
//
    override fun onDraw(textureId: Int): Int {


        //设置显示窗口
        GLES30.glViewport(0, 0, mWidth, mHeight)
        GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFrameBuffers[0])


        GLES30.glUseProgram(program)
        //这句话不一样
        GLES30.glUniformMatrix4fv(vMatrix, 1, false, matrix, 0)
        GLES30.glBindVertexArray(vao[0])
        GLES30.glActiveTexture(GLES30.GL_TEXTURE0)

        //因为这一层是摄像头后的第一层，所以需要使用扩展的  GL_TEXTURE_EXTERNAL_OES
        GLES30.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, textureId)
        GLES30.glDrawElements(GLES30.GL_TRIANGLE_STRIP,6,GLES30.GL_UNSIGNED_INT,0)
        GLES30.glUseProgram (GLES30.GL_NONE);
        GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
        GLES30.glBindTexture(GLES30.GL_TEXTURE_2D,GLES30.GL_NONE)
        //返回fbo的纹理id
        return mFrameBufferTextures[0]
    }





}